package com.example.exercise;

import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

import com.example.exercise.Base.User;
import com.example.exercise.MysqlUtil.ClassOpt;
import com.example.exercise.MysqlUtil.DBService;
import com.example.exercise.MysqlUtil.FindExist;

import java.util.ArrayList;
import java.util.List;

public class Cardjoin extends AppCompatActivity {


    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    EditText name,cardid;
    Spinner classroom;
    ImageView enjoin,ser;
    String CardId;
    String[] classstring;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cardjoin);
        InitView();
        cardread();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List list=ClassOpt.getAllClass();
                classstring = new String[list.size()];
                for (int i = 0; i <list.size() ; i++) {
                    classstring[i] = (String) list.get(i);
                }
                final ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,classstring);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        classroom.setAdapter(adapter);
                    }
                });


            }
        }).start();
        enjoin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (name.getText().toString().equals("")|| cardid.getText().toString().equals("")|| classroom.getSelectedItem().toString().equals("")){

                    Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();

                }else{
                    User user = new User();
                    user.setCardid(cardid.getText().toString());
                    user.setClassroom(classroom.getSelectedItem().toString());
                    user.setName(name.getText().toString());

                    final List<User> student = new ArrayList<>();
                    student.add(user);



                    new Thread(new Runnable(){
                        @Override
                        public void run() {

                            if (FindExist.getUserCard(cardid.getText().toString())!=0){

                                Looper.prepare();
                                Toast.makeText(getApplicationContext(),"卡号已存在，请检查",Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }else if (FindExist.getUserName(name.getText().toString(),classroom.getSelectedItem().toString())!=0){

                                Looper.prepare();
                                Toast.makeText(getApplicationContext(),"名字在此班级已存在，请检查",Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }
                            else {
                                DBService.insertUserData(student);
                                Looper.prepare();
                                Toast.makeText(getApplicationContext(),"录入成功",Toast.LENGTH_SHORT).show();

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        cardid.setText("");
                                        name.setText("");
                                    }
                                });

                                Looper.loop();}

                        }
                    }).start();
                }





            }
        });

        ser.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {


                cardid.setText("");
                name.setText("");


                return true;
            }
        });
        ser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (cardid.getText().toString().trim().equals("")){

                    Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();
                }else {

                    CardId = cardid.getText().toString();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final User user;
                            final List<User> list = DBService.getUserName(CardId);

                            if (list.size() == 0){

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        cardid.setText("无记录");
                                        name.setText("无记录");
                                    }
                                });
                                Looper.prepare();
                                Toast.makeText(getApplicationContext(), "此卡号数据库无记录", Toast.LENGTH_SHORT).show();
                                Looper.loop();


                            }else {
                                user = list.get(0);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "查询成功", Toast.LENGTH_SHORT).show();
                                        System.out.println(list.size() + "444");
                                        name.setText("    " + user.getName());
                                    }
                                });

                            }


                        }
                    }).start();
                }
            }
        });
    }


    private void InitView() {
        ser = findViewById(R.id.enjoin2);
        name  = findViewById(R.id.name);
        cardid = findViewById(R.id.cardid);
        classroom = findViewById(R.id.spinner2);
        enjoin =  findViewById(R.id.enjoin);
    }

    private void cardread() {

        //获取默认的NFC控制器
        //初始化NfcAdapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(getApplicationContext(), "设备不支持NFC!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        //初始化PendingIntent
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理
        pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    //启动
    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
    }

    //解析
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String CardId =ByteArrayToHexString(tagFromIntent.getId());
        cardid.setText(CardId);
        Toast.makeText(getApplicationContext(), CardId, Toast.LENGTH_LONG).show();
    }

    //转为16进制字符串
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";


        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);

    }
}